package com.example.cofeed.activity.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ada.common.cache.CacheManager;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.example.cofeed.MainActivity;
import com.example.cofeed.R;
import com.example.cofeed.activity.LoginActivity;
import com.example.cofeed.activity.MessageNotificationActivity;
import com.example.cofeed.activity.SearchActivity;
import com.example.cofeed.activity.WebViewActivity;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseFragment;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.Navigator;
import com.example.cofeed.even.LoginEeven;
import com.example.cofeed.widget.ChannelView;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

public class HomeFragment extends BaseFragment implements ChannelView.OnChannelListener {

    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tabs)
    SlidingTabLayout mTabs;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();

    protected ArrayList<Navigator> mNavigators = new ArrayList<>();
    protected List<Navigator> catdata = new ArrayList<>();
    protected List<Navigator> chdata = new ArrayList<>();
    private PagerAdapter mPagerAdapter;

    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    protected void initData() {

        String picture = SPUtils.getInstance().getString(SputilsConstant.PICTURE);

        if (ObjectUtils.isNotEmpty(picture)) {
            Glide.with(getActivity()).load(picture).into(mIvAvatar);
        }

        ApiService.navigator_index(this, new DialogCallback<LzyResponse<ArrayList<Navigator>>>(getActivity()) {
            @Override
            public void onSuccess(Response<LzyResponse<ArrayList<Navigator>>> response) {
                mNavigators.clear();
                mNavigators.addAll(response.body().data);

                initDaohang();

                CacheManager.putObject(SputilsConstant.NAVIGATOR, mNavigators);

            }
        });
//        }

        mTabs.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {


            }

            @Override
            public void onTabReselect(int position) {
                if (position == 1 && ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
                    ActivityUtils.startActivity(LoginActivity.class);
                }
            }
        });

    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    private void initDaohang() {
        mFragments.clear();
        mFragments = null;
        mFragments = new ArrayList<>();
        titles.clear();
        for (int i = 0; i < mNavigators.size(); i++) {
            Navigator navigator = mNavigators.get(i);
            HomeListFragment homeListFragment = HomeListFragment.newInstance(navigator);
            mFragments.add(homeListFragment);
            titles.add(navigator.title);
        }

        Navigator tuijian = new Navigator();
        tuijian.title = "推荐";
        mNavigators.add(0, tuijian);

        tuijian.catid = -1;
        tuijian.chid = -1;

//        mFragments.add(0, HomeListFragment.newInstance(-1, -1));
        mFragments.add(0, HomeListFragment.newInstance(tuijian));
        titles.add(0, "推荐");

        Navigator guanzhu = new Navigator();
        guanzhu.title = "关注";
        mNavigators.add(1, guanzhu);

        guanzhu.catid = -2;
        guanzhu.chid = -2;
        mFragments.add(1, HomeListFragment.newInstance(guanzhu));
        titles.add(1, "关注");

        mPagerAdapter = new PagerAdapter(getChildFragmentManager(), mFragments, titles);

        mViewPager.setAdapter(mPagerAdapter);
        mTabs.setViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                HomeListFragment homelistFragment = (HomeListFragment) mFragments.get(i);
                homelistFragment.updateArguments(mNavigators.get(i));


            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        mViewPager.setOffscreenPageLimit(titles.size() - 1);

        for (int i = 0; i < titles.size(); i++) {
            TextView textView = mTabs.getTitleView(i);
            String title = titles.get(i);
            switch (title.length()) {
                case 4:
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                    break;
                case 5:
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                    break;
                case 6:
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    break;
                default:
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    break;
            }

        }


    }

    public class PagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> mFragmentList;
        private List<String> mTitles;

        public PagerAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> titles) {
            super(fm);
            mFragmentList = fragmentList;
            mTitles = titles;
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            HomeListFragment fragment = (HomeListFragment) super.instantiateItem(container, position);
//            Tab tab = tabs.get(position);
            fragment.updateArguments(mNavigators.get(position));
            return fragment;
        }

    }

    @OnClick({R.id.ll_search, R.id.iv_msg, R.id.iv_menu, R.id.iv_avatar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_search:
//                Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                intent.putExtra(IntentKeyConstant.TYPE, 6);
//                startActivity(intent);
                ActivityUtils.startActivity(SearchActivity.class);
                break;
            case R.id.iv_msg:
                if (isLogin()) {
                    ActivityUtils.startActivity(MessageNotificationActivity.class);
                } else {
                    ActivityUtils.startActivity(LoginActivity.class);
                }
                break;
            case R.id.iv_menu:
//                if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))){
//                    ActivityUtils.startActivity(LoginActivity.class);
//                    return;
//                }
                if (ObjectUtils.isEmpty(mNavigators)) {
                    return;
                }
                showMenuDialog();
                break;
            case R.id.iv_avatar:
                if (isLogin()) {
                    ((MainActivity) getActivity()).mNavigationController.setSelect(3);
                } else {
                    ActivityUtils.startActivity(LoginActivity.class);
                }
                break;
        }
    }

    Dialog mDialog;
    ChannelView mChannelView;

    private void showMenuDialog() {
//        if (mDialog == null){
        mDialog = new Dialog(getActivity());
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_channel, null, false);
        mChannelView = inflate.findViewById(R.id.channelView);
//            if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))){
//                mChannelView.setEditTxt("未登录");
//            }
        inflate.findViewById(R.id.iv_close).setOnClickListener(v -> {
            if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
                mDialog.dismiss();
                return;
            }
            String[] channel = mChannelView.getMyChannel();
            ArrayList<Navigator> navigators = new ArrayList<>();
            ArrayList<Navigator> orcNavigators = new ArrayList<>();
            orcNavigators.addAll(mNavigators);
            orcNavigators.remove(0);
            orcNavigators.remove(0);
            for (String s : channel) {
                if (s.trim().contains("x")) {
                    s = s.replace("x", "").trim();
                }
                s = s.replace(" ", "");

                boolean isExit = false;
                for (Navigator navigator : orcNavigators) {
                    if (navigator.title.equals(s)) {
                        navigators.add(navigator);
                        isExit = true;
                        break;
                    }
                }
                if (!isExit) {
                    for (Navigator navigator : catdata) {
                        if (navigator.title.equals(s)) {
                            navigators.add(navigator);
                            isExit = true;
                            break;
                        }
                    }
                }
                if (!isExit) {
                    for (Navigator navigator : chdata) {
                        if (navigator.title.equals(s)) {
                            navigators.add(navigator);
                            break;
                        }
                    }
                }
            }

            ApiService.navigator_add_custom(this, navigators, new DialogCallback<LzyResponse<Object>>() {
                @Override
                public void onSuccess(Response<LzyResponse<Object>> response) {
                    CacheManager.putObject(SputilsConstant.NAVIGATOR, navigators);
                    mDialog.dismiss();
                    ApiService.navigator_index(this, new DialogCallback<LzyResponse<ArrayList<Navigator>>>(getActivity()) {
                        @Override
                        public void onSuccess(Response<LzyResponse<ArrayList<Navigator>>> response) {
                            mNavigators.clear();
                            mNavigators.addAll(response.body().data);

                            initDaohang();

                            CacheManager.putObject(SputilsConstant.NAVIGATOR, mNavigators);

                        }
                    });

                }
            });

        });
        mDialog.setContentView(inflate);

        ApiService.navigator_get_all(this, new DialogCallback<LzyResponse<Navigator>>(getActivity()) {
            @Override
            public void onSuccess(Response<LzyResponse<Navigator>> response) {
                catdata = response.body().data.catdata;
                chdata = response.body().data.chdata;
                String[] myChannel = new String[mNavigators.size()];
                for (int i = 0; i < mNavigators.size(); i++) {
                    myChannel[i] = mNavigators.get(i).title;
//                    if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))){

                    for (Iterator<Navigator> it = response.body().data.catdata.iterator(); it.hasNext(); ) {
                        Navigator navigator = it.next();
                        if (mNavigators.get(i).title.equals(navigator.title)) {
                            it.remove();
                            break;
                        }
                    }
                    for (Iterator<Navigator> it = response.body().data.chdata.iterator(); it.hasNext(); ) {
                        Navigator navigator = it.next();
                        if (mNavigators.get(i).title.equals(navigator.title)) {
                            it.remove();
                            break;
                        }
                    }
                }
//                }

                String[] recommendChannel0 = new String[response.body().data.catdata.size()];
                for (int i = 0; i < response.body().data.catdata.size(); i++) {
                    recommendChannel0[i] = response.body().data.catdata.get(i).title;
                }
                String[] recommendChannel = new String[response.body().data.chdata.size()];
                for (int i = 0; i < response.body().data.chdata.size(); i++) {
                    recommendChannel[i] = response.body().data.chdata.get(i).title;
                }

                Map<String, String[]> channels = new LinkedHashMap<>();
                channels.put("我的栏目", myChannel);
                if (ObjectUtils.isNotEmpty(recommendChannel0)) {
                    channels.put("更多品种", recommendChannel0);
                }
                if (ObjectUtils.isNotEmpty(recommendChannel)) {
                    channels.put("更多频道", recommendChannel);
                }

                mChannelView.setFixedChannel(0);
                mChannelView.setFixedChannel(1);
                mChannelView.setChannels(channels);
                mChannelView.setOnChannelItemClickListener(HomeFragment.this);


            }
        });


        Window localWindow = mDialog.getWindow();
        localWindow.setBackgroundDrawableResource(android.R.color.transparent);
        localWindow.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
            mDialog.setCanceledOnTouchOutside(true);
            mDialog.setCancelable(true);
        }

    }

    @Override
    public void channelItemClick(int itemId, String channelItem) {
        Log.i("channel", itemId + ".." + channelItem);
        if (mDialog != null) {

            boolean isExitItem = false;
            for (int i = 0; i < mNavigators.size(); i++) {
                if (channelItem.equals(mNavigators.get(i).title)) {
                    mViewPager.setCurrentItem(i);
                    isExitItem = true;
                    break;
                }
            }
            if (!isExitItem) {
                ArrayList<Navigator> navigators = new ArrayList<>();
                navigators.addAll(mNavigators);
                navigators.remove(0);
                navigators.remove(0);

                String s = channelItem;
                boolean isExit = false;
                for (Navigator navigator : mNavigators) {
                    if (navigator.title.equals(s)) {
                        navigators.add(navigator);
                        isExit = true;
                        break;
                    }
                }
                if (!isExit) {
                    for (Navigator navigator : catdata) {
                        if (navigator.title.equals(s)) {
                            navigators.add(navigator);
                            isExit = true;
                            break;
                        }
                    }
                }
                if (!isExit) {
                    for (Navigator navigator : chdata) {
                        if (navigator.title.equals(s)) {
                            navigators.add(navigator);
                            break;
                        }
                    }
                }
//                }

                ApiService.navigator_add_custom(this, navigators, new DialogCallback<LzyResponse<Object>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<Object>> response) {
                        CacheManager.putObject(SputilsConstant.NAVIGATOR, navigators);
                        mDialog.dismiss();
                        ApiService.navigator_index(this, new DialogCallback<LzyResponse<ArrayList<Navigator>>>(getActivity()) {
                            @Override
                            public void onSuccess(Response<LzyResponse<ArrayList<Navigator>>> response) {
                                mNavigators.clear();
                                mNavigators.addAll(response.body().data);

                                initDaohang();

                                for (int i = 0; i < mNavigators.size(); i++) {
                                    if (channelItem.equals(mNavigators.get(i).title)) {
                                        mViewPager.setCurrentItem(i);
                                        break;
                                    }
                                }

                                CacheManager.putObject(SputilsConstant.NAVIGATOR, mNavigators);

                            }
                        });

                    }
                });
            }

            mDialog.dismiss();
        }

    }

    @Override
    public void channelFinish(List<String> channels) {
        Log.i("channel", channels.toString());
    }

    @Override
    public void noLogin() {
        ActivityUtils.startActivity(LoginActivity.class);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Login(LoginEeven loginEeven) {
        initData();
        if (mDialog != null) {
            mChannelView.setEditTxt("编辑");
        }
    }

}
